package com.hotelmanage.manage.controllers;


import com.hotelmanage.manage.entities.Student;
import com.hotelmanage.manage.services.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("students")
public class StudentController {

    @Autowired
    StudentService studentService;

    @GetMapping
    public String displayStudents(Model model)
    {
        List<Student> students = studentService.getAll();
        model.addAttribute("students",students);
        return "students/list-students";
    }

    @GetMapping("/new")
    public String displayStudentForm(Model model)
    {

        Student aStudent= new Student();
        model.addAttribute("student",aStudent);
        return "students/new-student";


    }

    @GetMapping("/info")
    public String displayStudentInfo(Model model)
    {

        Student aStudent= new Student();
        model.addAttribute("student",aStudent);
        return "students/info-students";

    }

    @PostMapping("/save")
    public String createStudent(Model model, @Valid Student student, Errors errors)
    {
        if (errors.hasErrors()) return "students/new-student";
        studentService.save(student);
        return "redirect:/students";
    }

    @GetMapping("/delete")
    public String deleteStudent(@RequestParam("id") long theId,Model model)
    {

        Student theStudent =studentService.findByStudentId(theId);
        studentService.delete(theStudent);
        return"redirect:/students";
    }

}
